/*
Copyright (C) 2022-2024 Inspur Corp.

SPDX-License-Identifier: Apache-2.0
*/
package config

import (
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"icep/common/file"
	"icep/common/logger"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

var log = logger.GetLogger("config")

var Config *viper.Viper

func init() {
	go watchConfig()
	loadConfig()
}

// 监听配置更改
func watchConfig() {
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		//重新加载
		loadConfig()
	})
}

//加载配置
func loadConfig() {
	//获取项目的执行路径
	path, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	viper.SetConfigName("icep-config")
	viper.SetConfigType("yaml")
	configPath := filepath.Join(path, "config")
	if !file.DirExists(configPath) {
		configPath = filepath.Join(os.Getenv("GOPATH"), "src", "icep-service", "config")
	}
	viper.AddConfigPath(configPath)
	viper.AutomaticEnv()
	//viper.SetEnvPrefix("icep")
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
	err = viper.ReadInConfig()
	if err != nil {
		os.Exit(-1)
	}
	//全局配置
	Config = viper.GetViper()
}

func Get(key string, defaultValue string) string {
	log.Debugf("get config key = %s", key)
	value := Config.GetString(key)
	log.Debugf("get config value = %s", value)
	if value == "" || len(value) == 0 {
		return defaultValue
	}
	return value
}

func GetInt(key string, defaultValue int) int {
	log.Debugf("get config int key = %s", key)
	value := Config.GetString(key)
	if value == "" || len(value) == 0 {
		return defaultValue
	}
	ivalue, err := strconv.Atoi(value)
	if err != nil {
		ivalue = defaultValue
	}
	log.Debugf("get config int value = %d", ivalue)
	return ivalue
}

func GetBool(key string) bool {
	log.Debugf("get config bool key = %s", key)
	value := Config.GetBool(key)
	log.Debugf("get config bool value = %t", value)

	return value
}

func GetConfig() *viper.Viper {
	return Config
}
